﻿using System;
using System.Threading.Tasks;

namespace iTool.ClusterComponent
{
    public class LockService : iToolServiceBase, ILockService
    {
        TaskCompletionSource<Task> completionSource { get; set; }
        DateTime getLockTime { get; set; }
        TimeSpan timeoutDate { get; set; } = TimeSpan.FromSeconds(10);


        public override Task OnActivateAsync()
        {
            base.RegisterTimer(x => this.CheckTimeoutOwner(), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
            return base.OnActivateAsync();
        }

        public async Task FreedLockAsync()
        {
            this.completionSource.TrySetResult(Task.CompletedTask);
            await Task.CompletedTask;
        }

        public async Task GetLockAsync()
        {
            if (this.completionSource != null && !this.completionSource.Task.IsCompleted)
            {
                await this.completionSource.Task;
            }

            this.getLockTime = DateTime.Now;
            this.completionSource = new TaskCompletionSource<Task>();
            await Task.CompletedTask;
        }

        private async Task CheckTimeoutOwner() 
        {
            if (DateTime.Now - this.getLockTime > this.timeoutDate)
            {
                this.completionSource.TrySetResult(Task.CompletedTask);
            }

            await Task.CompletedTask;
        }
    }
}
